// webview 全局状态管理  - mqtt消息订阅
import { defineStore } from 'pinia'
import * as mqtt from 'mqtt'
import appEnvironment from '@/app-environments'
const {
    networkHosts: {
        mqttServer1: {fullHost: mqttHost},
    },
} = appEnvironment

export type T_SubscribeTopic = {
    topicName: string
    /** 订阅消息来源的标识，便于后续过滤 */
    sourceKey?: string
}
export interface T_Mqtt {
    mqttClient?: mqtt.MqttClient
    /** mqtt 连接地址 */
    connectUrl: string
    /** 是否连接 */
    onConnect: boolean
    clientId?: string
    /** 已订阅的主题列表 */
    onSubscribeTopics: Array<T_SubscribeTopic>
}
interface T_GlobalState {
    mqtt: T_Mqtt
}

export const useWebGlobalStore = defineStore('webviewGlobalStore', {
    state(): T_GlobalState {
        return {
            mqtt: {
                connectUrl: mqttHost || '',
                onConnect: false,
                clientId: '',
                onSubscribeTopics: [],
                mqttClient: undefined
            }
        }
    },
    actions: {
        initMqttClient(options: mqtt.IClientOptions, url?: string ) {
            const mqttInstance = this.mqtt as any
            console.log('初始化mqtt ', url, mqttInstance.mqttClient)
            if (mqttInstance.mqttClient) return
            let connectUrl = url || this.mqtt.connectUrl
            if(!connectUrl){
                console.log('mqtt client error: ', 'mqtt connect url is empty')
                return
            }
            connectUrl = url || this.mqtt.connectUrl+'/mqtt'
            mqttInstance.mqttClient = mqtt.default.connect(connectUrl, options)
            mqttInstance.mqttClient.on('connect', () => {
                mqttInstance.onConnect = true
                console.log('mqtt client connect success: ', mqttInstance.mqttClient)
            })
            mqttInstance.mqttClient.on('error', (err: Error) => {
                console.log('mqtt client error: ', err)
            })
            mqttInstance.mqttClient.on('close', () => {
                mqttInstance.onConnect = false
            })
        },
        /** 订阅主题 */
        subscribeTopic(
            topic: string,
        ): Promise<boolean> | boolean {
            if (!topic || !this.mqtt.onConnect) return false
            if(this.mqtt.onSubscribeTopics.find(item=>item.topicName===topic)){
                console.log('dingyue', topic)
                return false
            }
            return new Promise((resolve, reject) => {
                this.mqtt.mqttClient?.subscribe(topic, { qos: 0 }, (err) => {
                    if (err) {
                        console.log('subscribe error: ', err)
                        reject(err)
                    } else {
                        console.log('subscribe success: ', topic)
                        if(this.mqtt.onSubscribeTopics.find(item=>item.topicName!==topic)){
                            this.mqtt.onSubscribeTopics.push({topicName: topic})
                        }
                        resolve(true)
                    }
                })
            })
        },
        /** 取消订阅主题 */
        unsubscribeTopic(topic: string) {
            if (!topic || !this.mqtt.onConnect) return false
            return new Promise((resolve, reject) => {
                this.mqtt.mqttClient?.unsubscribe(topic, (err) => {
                    if (err) {
                        console.log('unsubscribe error: ', err)
                        reject(err)
                    } else {
                        console.log('unsubscribe success: ', topic)
                        this.mqtt.onSubscribeTopics = this.mqtt.onSubscribeTopics.filter((item=>item.topicName!==topic))
                        resolve(true)
                    }
                })
            })
        },
        reset() {
            this.mqtt.onSubscribeTopics.forEach((item) => {
                item.topicName && this.unsubscribeTopic(item.topicName)
            })
            this.mqtt.mqttClient?.removeAllListeners()
            this.mqtt.mqttClient?.end()
            this.mqtt.mqttClient = undefined
            this.mqtt.onConnect = false
            this.mqtt.onSubscribeTopics = []
        }
    }
})

/** 用于webview全局状态管理 */
export const useStore_WebGlobalStore = useWebGlobalStore
